<template>
  <div class="newsList" ref="newsList">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-cell
          v-for="(item, index) in newsList"
          :key="index"
          :title="item.title"
          @click="$router.push(`/home/detail?id=${item.art_id}`)"
        >
          <template #label
            ><van-grid
              v-if="item.cover.type !== 0"
              :border="false"
              :column-num="3"
            >
              <van-grid-item
                v-for="(subitem, subindex) in item.cover.images"
                :key="subindex"
              >
                <van-image :src="subitem" />
              </van-grid-item>
            </van-grid>
            <div class="datail">
              <span>{{ item.aut_name }}</span>
              <span>{{ item.comm_count }}评论</span>
              <span>{{ item.pubdate | timefromnow }}</span>
              <van-icon class="myicon" name="cross" />
            </div>
          </template>
        </van-cell>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getNewsListAPI } from "@/api";
export default {
  props: ["channel_id"],
  data() {
    return {
      newsList: [],
      // 控制list组件的加载状态
      loading: false,
      // 判断list组件的数据是否加载完毕
      finished: false,
      timestamp: Date.now(),
      refreshing: false,
      scrollTop: 0,
    };
  },

  mounted() {
    this.$refs.newsList.onscroll = () => {
      this.scrollTop = this.$refs.newsList.scrollTop;
    };
  },

  activated() {
    this.$refs.newsList.scrollTop = this.scrollTop;
  },

  methods: {
    onRefresh() {
      // 清空列表数据
      this.finished = false;

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true;
      this.onLoad();
    },

    async onLoad() {
      if (this.refreshing) {
        this.newsList = [];
        this.timestamp = Date.now();
        setTimeout(() => {
          this.refreshing = false;
        }, 400);
      }
      const res = await getNewsListAPI({
        channel_id: this.channel_id,
        timestamp: this.timestamp,
      });
      // console.log(res);
      // res.data.data中 pre_timestamp是下次请求的时间戳
      // 每次请求都会覆盖原数据，这里需要将旧数据也保存到数组中去
      this.newsList = [...this.newsList, ...res.data.data.results];

      this.timestamp = res.data.data.pre_timestamp;
      this.loading = false;

      // 判断是否还有后续数据
      if (this.timestamp === null) {
        this.finished = true;
      }
    },
  },
};
</script> 

<style lang="less">
.newsList {
  position: fixed;
  left: 0;
  top: 90px;
  bottom: 50px;
  width: 100%;
  overflow: auto;
  .datail {
    span {
      margin-right: 30px;
    }
    .myicon {
      float: right;
      color: #999 !important;
    }
  }
}
</style>